angular.module("driver").controller("AccountCtrl", ['$scope', '$meteor',

  '$rootScope', '$state', '$ionicPopup', 'Map', '$ionicModal', 'Translate',
  function($scope, $meteor, $rootScope, $state, $ionicPopup, Map, $ionicModal, Translate) {

    $ionicModal.fromTemplateUrl('client/driver/views/forgotPassword.ng.html', {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.modal = modal;
    });
    $scope.found = function() {
      $scope.modal.show();
    };
    $scope.closeye = function() {
      $scope.modal.hide();
    };
    //当我们用到模型时，清除它！
    $scope.$on('$destroy', function() {
      $scope.modal.remove();
    });
    // 当隐藏的模型时执行动作
    $scope.$on('modal.hide', function() {
      // 执行动作
    });
    // 当移动模型时执行动作
    $scope.$on('modal.removed', function() {
      // 执行动作
    });

    $meteor.subscribe('userData');
    $rootScope.$watch('currentUser.show', function(newValue, oldValue) {
      if ($rootScope.currentUser)
        $meteor.call('updateShow', newValue);
    }, true);

    $scope.info = {};

    $scope.login = function() {

      if (!$scope.info.username || !$scope.info.password) {
        $scope.showAlert('登录失败', '请输入账号和密码!');
        return;
      }

      var geo = Map.geolocation;
      Meteor.loginWithPassword($scope.info.username, $scope.info.password,
        function(error) {
          if (error) {
            $scope.showAlert('登录失败', Translate.translate(error.reason));
          }
          else {
            console.log(geo);
            $meteor.call('updateLocation', Map.getLocation());
            //Map.geolocation.getCurrentPosition();
          }
        });


    };

    $scope.finish = function () {
      if(!$scope.info.password || !$scope.info.newpassword || !$scope.info.confixpassword) {
        $scope.showAlert('重设失败', '每一项都需要填写!');

        return;
      }

      if ($scope.info.confixpassword !== $scope.info.newpassword) {
        $scope.showAlert('重设失败', '密码不一致!');
        
        return;
      }
      else {
        $scope.modal.hide();
        $state.go('main.amap');
      }

      // Accounts.changePassword = function($scope.info.password, $scope.info.newpassword, 
      //   function(error) {
        
      // }) 
    }

    
    Accounts.forgotPassword = function(options, callback) {
      if (!options.email)
        throw new Error("Must pass options.email");
      Accounts.connection.call("forgotPassword", options, callback);
    };
    Accounts.resetPassword = function(token, newPassword, callback) {
      check(token, String);
      check(newPassword, String);

      if (!newPassword) {
        callback(new Meteor.Error(400, "Password may not be empty"));
        return;
      }

      Accounts.callLoginMethod({
        methodName: 'resetPassword',
        methodArguments: [token, Accounts._hashPassword(newPassword)],
        userCallback: callback
      });
    };
    Accounts.verifyEmail = function(token, callback) {
      if (!token)
        throw new Error("Need to pass token");

      Accounts.callLoginMethod({
        methodName: 'verifyEmail',
        methodArguments: [token],
        userCallback: callback
      });
    };
    Accounts.sendResetPasswordEmail = function(userId, email) {
      // Make sure the user exists, and email is one of their addresses.
      var user = Meteor.users.findOne(userId);
      if (!user)
        throw new Error("Can't find user");
      // pick the first email if we weren't passed an email.
      if (!email && user.emails && user.emails[0])
        email = user.emails[0].address;
      // make sure we have a valid email
      if (!email || !_.contains(_.pluck(user.emails || [], 'address'), email))
        throw new Error("No such email for user.");

      var token = Random.secret();
      var when = new Date();
      var tokenRecord = {
        token: token,
        email: email,
        when: when
      };
      Meteor.users.update(userId, {
        $set: {
          "services.password.reset": tokenRecord
        }
      });
      // before passing to template, update user object with new token
      Meteor._ensure(user, 'services', 'password').reset = tokenRecord;

      var resetPasswordUrl = Accounts.urls.resetPassword(token);

      var options = {
        to: email,
        from: Accounts.emailTemplates.resetPassword.from ? Accounts.emailTemplates.resetPassword.from(user) : Accounts.emailTemplates.from,
        subject: Accounts.emailTemplates.resetPassword.subject(user),
        text: Accounts.emailTemplates.resetPassword.text(user, resetPasswordUrl)
      };

      if (typeof Accounts.emailTemplates.resetPassword.html === 'function')
        options.html =
        Accounts.emailTemplates.resetPassword.html(user, resetPasswordUrl);

      if (typeof Accounts.emailTemplates.headers === 'object') {
        options.headers = Accounts.emailTemplates.headers;
      }

      Email.send(options);
    };

    $scope.logout = function() {
      Meteor.logout(function(error) {
        if (error)
          $scope.showAlert(error.reason, error.message);
        if (Map.instance) {
          Map.instance.clearMap();
          console.log('Map.instance.clearMap();');
        }
      });
    };
    // An alert dialog
    $scope.showAlert = function(title, temp) {
      var alertPopup = $ionicPopup.alert({
        title: title,
        template: temp,
        okType: 'button-royal',
        okText: '确定'
      });
      alertPopup.then(function(res) {
        //console.log('Thank you for not eating my delicious ice cream cone');
      });
    };

    $scope.isDriver = function() {
      //console.log(this.userId)
      if (!Meteor.user()) return false;

      return Roles.userIsInRole(Meteor.user()._id, 'driver');
    };
  }
]);
